package com.fanghuyun.iswaf.function;

import java.io.File;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.fanghuyun.iswaf.common.ClientLogger;
import com.fanghuyun.iswaf.common.Constants;
import com.fanghuyun.iswaf.common.SysConfig;
import com.fanghuyun.iswaf.filter.DoFilter;
import com.fanghuyun.iswaf.util.StringUtil;

public class WebShell extends DoFilter{
	
	private static Logger logger = Logger.getLogger("iswaf");
	
	public static boolean webShell(HttpServletRequest request,Properties properties) {
		String filePath = SysConfig.getRequestFileRealPath(request);
		if(StringUtil.isNotEmpty(filePath) && new File(filePath).exists()){
			try {
				if(isWebShell(new File(filePath),properties)){
					ClientLogger.addAttackLogs(request, Constants.SYS_FUNCTION_WEBSHELL);
					return true;
				}
			} catch (Exception e) {
				logger.error(e);
			}
		}
		return false;
	}
	
	public static boolean isWebShell(File f,Properties properties) {
		if(StringUtil.isNotEmpty(f) && f.exists()){
			try {
				String packages = properties.getProperty("function.webshell.webshell_package");
				String pr = "import\\s?=\\s?\".*("+(StringUtils.join(packages.split(","),"|").replaceAll("\\.", "\\\\."))+")\\..*s?\"";
				String fileContent = FileUtils.readFileToString(f.isDirectory()&&new File(f.getAbsolutePath().replaceAll("\\\\", "/")+"/index.jsp").exists()?new File(f.getAbsolutePath().replaceAll("\\\\", "/")+"/index.jsp"):f);
				return Pattern.compile(pr,Pattern.DOTALL).matcher(fileContent).find();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}
}
